package org.jeecg.modules.monitoring.j_monitoring.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.monitoring.j_monitoring.entity.MDocumentManagement;
import org.jeecg.modules.monitoring.j_monitoring.service.IMDocumentManagementService;
import org.jeecg.modules.monitoring.j_monitoring.vo.DocTreeNode;
import org.jeecg.modules.monitoring.j_monitoring.vo.MDocumentManagementPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

 /**
 * @Description: 文档管理
 * @Author: xiaoyq
 * @Date:   2023-06-26
 * @Version: V1.0
 */
@Api(tags="文档管理")
@RestController
@RequestMapping("/j_monitoring/mDocumentManagement")
@Slf4j
public class MDocumentManagementController extends JeecgController<MDocumentManagement, IMDocumentManagementService> {
	/**
	 * 分页列表查询
	 *
	 * @param mDocumentManagement
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "文档管理-分页列表查询")
	@RequiresPermissions("文档管理:查询")
	@ApiOperation(value="文档管理-分页列表查询", notes="文档管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<MDocumentManagement>> queryPageList(MDocumentManagement mDocumentManagement,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MDocumentManagement> queryWrapper = QueryGenerator.initQueryWrapper(mDocumentManagement, req.getParameterMap());
		Page<MDocumentManagement> page = new Page<MDocumentManagement>(pageNo, pageSize);
		IPage<MDocumentManagement> pageList = service.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 /**
	  * 查询子目录
	  *
	  * @param parentIds 父ID（多个采用半角逗号分割）
	  * @return 返回 key-value 的 Map
	  */
	 @RequiresPermissions("文档管理:查询")
	 @GetMapping("/querySubTree")
	 public Result querySubTree(@RequestParam("parentIds") String parentIds) {
		 try {
			 LambdaQueryWrapper<MDocumentManagement> query = new LambdaQueryWrapper<>();
			 List<String> parentIdList = Arrays.asList(parentIds.split(","));
			 query.in(MDocumentManagement::getParentId, parentIdList);
			 query.orderByAsc(MDocumentManagement::getCreateTime);
			 List<MDocumentManagement> dataList = service.list(query);
			 List<DocTreeNode> arrayList = new ArrayList<>();

			 List<DocTreeNode> resultList = new ArrayList<>();
			 DocTreeNode model;
			 DocTreeNode pNode;
			 List<DocTreeNode> children;
			 if(dataList.size() > 0) {
				 Map<String, DocTreeNode> listMap = new HashMap(5);
				 for(MDocumentManagement dataItem : dataList) {
					 model = new DocTreeNode(dataItem);
					 arrayList.add(model);
					 listMap.put(model.getId(),model);
				 }

				 for(DocTreeNode treeNode : arrayList) {
					 if(listMap.containsKey(treeNode.getPid())){
						 pNode = listMap.get(treeNode.getPid());
						 children = pNode.getChildren();
						 if(children==null){
							 children = new ArrayList<>();
							 pNode.setChildren(children);
						 }
						 children.add(treeNode);
					 }
					 else{
						 resultList.add(treeNode);
					 }
				 }
			 }
			 return Result.ok(dataList);
		 } catch (Exception e) {
			 log.error(e.getMessage(), e);
			 return Result.error("批量查询子目录失败：" + e.getMessage());
		 }
	 }

	 @RequiresPermissions("文档管理:查询")
	 @RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
	 public Result<List<DocTreeNode>> queryTreeList() {
		 Result<List<DocTreeNode>> result = new Result<List<DocTreeNode>>();

		 List<DocTreeNode> treeList = this.service.searchByKeyWord(null,"0");
		 if (treeList == null || treeList.size() == 0) {
			 result.setSuccess(false);
			 result.setMessage("未查询匹配数据！");
			 return result;
		 }
		 result.setResult(treeList);
		 return result;
	 }

	 /**
	  * <p>
	  * 文档搜索功能方法,根据关键字模糊搜索相关文档
	  * </p>
	  *
	  * @param keyWord
	  * @return
	  */
	 @RequiresPermissions("文档管理:查询")
	 @RequestMapping(value = "/searchBy", method = RequestMethod.GET)
	 public Result<List<DocTreeNode>> searchBy(@RequestParam(name = "keyWord", required = false) String keyWord,@RequestParam(name = "parentId", required = false) String parentId) {
		 Result<List<DocTreeNode>> result = new Result<List<DocTreeNode>>();
		 if(keyWord!=null && !"".equals(keyWord)){
			 keyWord = "%" + keyWord + "%";
		 }
		 List<DocTreeNode> treeList = this.service.searchByKeyWord(keyWord,parentId);
		 if (treeList == null || treeList.size() == 0) {
			 result.setSuccess(false);
			 result.setMessage("未查询匹配数据！");
			 return result;
		 }
		 result.setResult(treeList);
		 return result;
	 }

	/**
	 *   添加
	 *
	 * @param mDocumentManagementPage
	 * @return
	 */
	@AutoLog(value = "文档管理-添加")
	@ApiOperation(value="文档管理-添加", notes="文档管理-添加")
	@RequiresPermissions("文档管理:添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody MDocumentManagementPage mDocumentManagementPage) {
		MDocumentManagement mDocumentManagement = new MDocumentManagement();
		BeanUtils.copyProperties(mDocumentManagementPage, mDocumentManagement);
		service.saveMain(mDocumentManagement);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param mDocumentManagementPage
	 * @return
	 */
	@AutoLog(value = "文档管理-编辑")
	@ApiOperation(value="文档管理-编辑", notes="文档管理-编辑")
	@RequiresPermissions("文档管理:编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody MDocumentManagementPage mDocumentManagementPage) {
		MDocumentManagement mDocumentManagement = new MDocumentManagement();
		BeanUtils.copyProperties(mDocumentManagementPage, mDocumentManagement);
		MDocumentManagement mDocumentManagementEntity = service.getById(mDocumentManagement.getId());
		if(mDocumentManagementEntity==null) {
			return Result.error("未找到对应数据");
		}
		service.updateMain(mDocumentManagement);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "文档管理-通过id删除")
	@ApiOperation(value="文档管理-通过id删除", notes="文档管理-通过id删除")
	@RequiresPermissions("文档管理:删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		service.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "文档管理-批量删除")
	@ApiOperation(value="文档管理-批量删除", notes="文档管理-批量删除")
	@RequiresPermissions("文档管理:批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.service.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@RequiresPermissions("文档管理:查询")
	@ApiOperation(value="文档管理-通过id查询", notes="文档管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<MDocumentManagement> queryById(@RequestParam(name="id",required=true) String id) {
		MDocumentManagement mDocumentManagement = service.getById(id);
		if(mDocumentManagement==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(mDocumentManagement);

	}


    /**
    * 导出excel
    *
    * @param request
    * @param mDocumentManagement
    */
	@RequiresPermissions("文档管理:导出")
    @RequestMapping(value = "/exportXls", method = RequestMethod.GET)
	@ApiOperation(value="文档管理-导出", notes="文档管理-导出")
    public ModelAndView exportXls(HttpServletRequest request, MDocumentManagement mDocumentManagement) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<MDocumentManagement> queryWrapper = QueryGenerator.initQueryWrapper(mDocumentManagement, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
       String selections = request.getParameter("selections");
       if(oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id",selectionList);
       }
       //Step.2 获取导出数据
       List<MDocumentManagement> mDocumentManagementList = service.list(queryWrapper);

      // Step.3 组装pageList
      List<MDocumentManagementPage> pageList = new ArrayList<MDocumentManagementPage>();
      for (MDocumentManagement main : mDocumentManagementList) {
          MDocumentManagementPage vo = new MDocumentManagementPage();
          BeanUtils.copyProperties(main, vo);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "文档管理列表");
      mv.addObject(NormalExcelConstants.CLASS, MDocumentManagementPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("文档管理数据", "导出人:"+sysUser.getRealname(), "文档管理"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
	@RequiresPermissions("文档管理:导入")
	@ApiOperation(value="文档管理-导入", notes="文档管理-导入")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<MDocumentManagementPage> list = ExcelImportUtil.importExcel(file.getInputStream(), MDocumentManagementPage.class, params);
              for (MDocumentManagementPage page : list) {
                  MDocumentManagement po = new MDocumentManagement();
                  BeanUtils.copyProperties(page, po);
                  service.saveMain(po);
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
